import { NextRequest, NextResponse } from 'next/server';
import { VideoService } from '@/app/lib/DataBase/database';

// 模拟获取当前用户ID的函数（实际项目中应该从认证系统获取）
const getCurrentUserId = (request: NextRequest): number | undefined => {
  // 在实际项目中，这里应该从JWT token或session中获取用户ID
  // 这里为了演示，我们使用一个固定值或从查询参数中获取
  const userIdParam = request.nextUrl.searchParams.get('userId');
  return userIdParam ? parseInt(userIdParam, 10) : undefined;
};

// 获取所有视频
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const limit = parseInt(searchParams.get('size') || '20');
    const page = parseInt(searchParams.get('page') || '1');
    const offset = (page - 1) * limit;
    
    // 获取当前用户ID（实际项目中应该从认证系统获取）
    const userId = getCurrentUserId(request);
    
    // 使用新方法获取视频列表，包含评分信息
    const videos = await VideoService.getAllVideosWithRatings(limit, offset, userId);
    
    // 单独获取总数（因为getAllVideosWithRatings不返回总数）
    const totalResult = await VideoService.getAllVideos(1, 0);
    const totalCount = totalResult[0]?.totalCount || 0;
    
    return NextResponse.json({ 
      success: true, 
      data: videos,
      pagination: {
        size: limit,
        page: page,
        total: totalCount
      }
    });
  } catch (error) {
    console.error('获取视频列表失败:', error);
    return NextResponse.json({ 
      success: false, 
      message: '获取视频列表失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}

// 添加新视频
export async function POST(request: NextRequest) {
  try {
    const videoData = await request.json();
    console.log('⏰ ~ POST ~ videoData:', videoData)
    
    // 验证必需字段
    if (!videoData.id || !videoData.title || !videoData.category) {
      return NextResponse.json({ 
        success: false, 
        message: '缺少必需字段: id, title, category' 
      }, { status: 400 });
    }
    videoData.id = videoData.id || (Date.now() + Math.round(Math.random() * 10000))
    const result = await VideoService.addVideo(videoData);
    
    return NextResponse.json({ 
      success: true, 
      data: result,
      message: '视频添加成功' 
    });
  } catch (error) {
    console.error('添加视频失败:', error);
    return NextResponse.json({ 
      success: false, 
      message: '添加视频失败',
      error: error instanceof Error ? error.message : '未知错误'
    }, { status: 500 });
  }
}
